//
//  HMOAuthViewController.swift
//  WeiBo
//
//  Created by Feng on 2017/6/5.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit
import SVProgressHUD

//创建AppKey,Redirect_Uri
let AppKey = "1223762572"
let Redirect_Uri = "http://www.itcast.cn"

class HMOAuthViewController: UIViewController {

    //创建webView
    var webView: UIWebView = UIWebView()
    
    //重写loadView()
    override func loadView() {
        
        view = webView
        
        //设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadWebView()
        setupUI()
    }

    //加载webView
    private func loadWebView()
    {
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)")
        
        let request = URLRequest(url: url!)
        
        webView.loadRequest(request)
        
//        print(url)
    }
    
    private func setupUI()
    {
        //设置导航栏信息
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, target: self, action: #selector(cancel))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imageName: nil, target: self, action: #selector(autoFill))
        
        navigationItem.title = "微博登录"
    }

    //MARK: --取消登录
    @objc private func cancel()
    {
        self.dismiss(animated: true, completion: nil)
    }
    //MARK: --自动填充
    @objc private func autoFill()
    {
        print("自动填充")
        
        let jsString = "document.getElementById('userId').value='13814734648';document.getElementById('passwd').value = 'safcc@423710'"
        
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
//    //MARK: --加载Access_Token
//    fileprivate func requestAccessToken(code: String)
//    {
//        NetworkTools.shareTools.requestAccessToken(code: code, callBack: { (response, error) in
//            
//            if error != nil
//            {
//                print("Access_Token加载出错 = \(error!)")
//            }
//            else
//            {
//                if let res = response
//                {
//                    print("res = \(res)")
//                    //创建账号模型
//                    let account = HMUserAccount(dict: res as! [String : Any])
//                    self.requestUserAccount(userAccount: account)
//                }
//            }
//        })
//    }
//    
//    //MARK: --加载用户信息
//    fileprivate func requestUserAccount(userAccount: HMUserAccount)
//    {
//        NetworkTools.shareTools.requestUserInfo(access_token: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
//            
//            if error != nil
//            {
//                print("用户信息加载出错 = \(error!)")
//                return
//            }
//            else
//            {
//                if let userResult = response
//                {
////                    print("userResult = \(userResult)")
//                    //将name,avatar_large 数据增入用户模型
//                    let userDict: [String: Any] = userResult as! [String : Any]
//                    userAccount.name = userDict["name"] as? String
//                    userAccount.avatar_large = userDict["avatar_large"] as? String
//                }
//            }
//        }
//    }
}

//MARK: --webView代理方法
extension HMOAuthViewController: UIWebViewDelegate
{
    //截获URL
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request)
        
        let urlStr = request.url!.absoluteString
       
        if urlStr.hasPrefix(Redirect_Uri) == true
        {
            //获取URL中的参数字符串
            if let query = request.url?.query, query.hasPrefix("code=")
            {
                //截取授权码
                let code = query.substring(from: "code=".endIndex)
            
                //加载Access_Token
                //记载用户信息
                //            requestAccessToken(code: code)
                HMUserAccountViewModel.sharedUserAccount.requestAccessToken(code: code, callBack: { (isSuccess: Bool) in
                    
                    if isSuccess
                    {
                        print("登录成功")
                        //不往下走?
                        self.dismiss(animated: false, completion: { 
                            //发送通知,更换根控制器
                            print("....")
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: SwitchRootViewControllerNotification), object: self)
                        })
                        //发送通知,更换根控制器
//                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: SwitchRootViewControllerNotification), object: self)
                    }
                    else
                    {
                        print("登录失败")
                    }
                })
            }
            else
            {
                dismiss(animated: true, completion: nil)
            }
            //不加载
            return false
        }
        return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
}
